package com.acane.instagram.service.impl;


import com.acane.instagram.mapper.UserMapper;
import com.acane.instagram.pojo.Result;
import com.acane.instagram.pojo.User;
import com.acane.instagram.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl
        extends ServiceImpl<UserMapper, User>
        implements UserService {


        @Autowired
        private UserMapper userMapper;

        private final String uploadDir = "E:\\uploads\\";


    @Override
    public User getUserById(String userId) {
        return userMapper.selectById(userId); // 需要Mapper支持String类型ID查询
    }

    @Override
    public void updateUserAvatar(String userId, String fileName) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        user.setAvatar(fileName);
        userMapper.updateById(user);
    }

    @Override
    public Result getRecommendUserList(String userId) {
        List<String> recommendUserIds = userMapper.getRecommendUserId(userId);
        if (recommendUserIds.isEmpty()) {
            return Result.success(new ArrayList<>());
        }
        List<User> recommendUserList = userMapper.getRecommendUserList(recommendUserIds);
        return Result.success(recommendUserList);
    }

    @Override
    public Boolean judgeFollowed(String followingId, String followerId) {
        if (userMapper.judgeFollowed(followingId, followerId) == null) {
            return false;
        }
        int status = userMapper.judgeFollowed(followingId, followerId);
        return status == 1;
    }

    @Override
    public List<User> getMessageList(String userName) {
        return userMapper.getMessageList(userName);
    }

    @Override
    public User getUserByUserName(String userName) {
        return userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, userName));
    }

    @Override
    public int getPostCount(String userId) {
        return userMapper.getPostCount(userId);
    }

    @Override
    public int getFollowerCount(String userId) {
        return userMapper.getFollowerCount(userId);
    }

    @Override
    public int getFollowingCount(String userId) {
        return userMapper.getFollowingCount(userId);
    }

    @Override
    public List<User> searchUser(String keyword) {
        return userMapper.searchUser(keyword);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, username));
    }


    @Override
        public String uploadAvatar(Integer userId, MultipartFile file) throws IOException {
            if (file.isEmpty()) {
                return "File is empty";
            }

            // Generate a unique file name
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            Path filePath = Paths.get(uploadDir, fileName);

            // Create upload directory if it doesn't exist
            Files.createDirectories(filePath.getParent());

            // Save the file to the server
            file.transferTo(filePath.toFile());

            // Update the user's avatar field in the database
            User user = userMapper.selectById(userId);
            if (user != null) {
                user.setAvatar(fileName);
                userMapper.updateById(user);
                return "Avatar uploaded successfully";
            } else {
                return "User not found";
            }
        }

    @Override
    public User findUser(String userName, String password) {
        return userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, userName)
                .eq(User::getPassword, password));
    }
}
